package com.business.lgh.naocs.naming.controllers;

import com.business.lgh.nacos.api.common.Constants;
import com.business.lgh.nacos.api.naming.utils.JacksonUtils;
import com.business.lgh.nacos.api.naming.utils.NamingUtils;
import com.business.lgh.nacos.core.auth.annotation.ActionTypes;
import com.business.lgh.nacos.core.auth.annotation.Secured;
import com.business.lgh.naocs.naming.constant.UtilsAndCommons;
import com.business.lgh.naocs.naming.core.ServiceManager;
import com.business.lgh.naocs.naming.core.pojo.ClusterInfo;
import com.business.lgh.naocs.naming.core.pojo.ServiceDetailInfo;
import com.business.lgh.naocs.naming.core.pojo.ServiceView;
import com.business.lgh.naocs.naming.core.pojo.ServiceWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.controllers
 * @date 2020/6/25 2:08 上午
 */
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/catalog")
public class CatalogController {

    @Autowired
    ServiceManager serviceManager;

    /**
     * http://127.0.0.1:8848/nacos/v1/ns/catalog/services?
     * hasIpCount=true&withInstances=false&pageNo=1&pageSize=10&serviceNameParam=
     * &groupNameParam=
     * &accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTU5MzAzNzU1NH0.4XmNJr9sKX5-3zsI2LdNVSgRh58xoTl6EWfdfsblB_c&namespaceId=
     * @param withInstances  是否要返回实例
     * @param namespaceId  筛选条件
     * @param pageNo
     * @param pageSize
     * @param serviceName  筛选条件
     * @param groupName   筛选条件
     * @param containedInstance  筛选条件
     * @param hasIpCount   是否要统计ip数量
     * @return
     */
    @GetMapping("/services")
    public Object listDetail(@RequestParam(required = false) boolean withInstances,
                             @RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
                             @RequestParam(required = false) int pageNo,
                             @RequestParam(required = false) int pageSize,
                             @RequestParam(name = "serviceNameParam", defaultValue = StringUtils.EMPTY) String serviceName,
                             @RequestParam(name = "groupNameParam", defaultValue = StringUtils.EMPTY) String groupName,
                             @RequestParam(name = "instance", defaultValue = StringUtils.EMPTY) String containedInstance,
                             @RequestParam(required = false) boolean hasIpCount
    ) {
        //参数检查，如果服务名称和组名为空则返回空，否则获取组装下
        String param = StringUtils.isBlank(serviceName) && StringUtils.isBlank(groupName) ?
                StringUtils.EMPTY : StringUtils.EMPTY;

        //是否返回实例信息
        if (withInstances) {
            List<ServiceDetailInfo> serviceDetailInfoList = new ArrayList<>();

            List<ServiceWrapper> services = new ArrayList<>(8);
            //熟悉的servicemanager获取服务
            serviceManager.getPagedService(namespaceId, pageNo, pageSize, param, StringUtils.EMPTY, services, false);

            /**
             * 遍历所有服务包装成ServiceDetailInfo
             */
            for (ServiceWrapper service : services) {
                ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo();
                serviceDetailInfo.setServiceName((service.getName()));
                serviceDetailInfo.setGroupName((service.getName()));
//                serviceDetailInfo.setMetadata(service.getMetadata());

//                Map<String, ClusterInfo> clusterInfoMap = getStringClusterInfoMap(service);
//                serviceDetailInfo.setClusterMap(clusterInfoMap);
//                serviceDetailInfoList.add(serviceDetailInfo);
            }

            return serviceDetailInfoList;
        }

        //创建一个空的{}
        ObjectNode result = JacksonUtils.createEmptyJsonNode();

        List<ServiceWrapper> services = new ArrayList<>();

        //存储服务到服务列表，并且返回服务数量
        //          serviceManager.getPagedService(namespaceId, pageNo, pageSize, param, StringUtils.EMPTY, services, false);
        int total = serviceManager.getPagedService(namespaceId, pageNo - 1, pageSize, param, containedInstance, services, hasIpCount);

        //如果服务列表为空，则直接参数替换返回
        if (CollectionUtils.isEmpty(services)) {
            result.replace("serviceList", JacksonUtils.transferToJsonNode(Collections.emptyList()));
            result.put("count", 0);
            return result;
        }

        //包装成serviceView视图
        List<ServiceView> serviceViews = new LinkedList<>();
        for (ServiceWrapper service : services) {
            ServiceView serviceView = new ServiceView();
            serviceView.setName(NamingUtils.getServiceName(service.getName()));
            serviceView.setGroupName(NamingUtils.getGroupName(service.getName()));
            //主要是有集群个数，ip个数，和健康个数
            serviceView.setClusterCount(service.getClusterMap().size());
            serviceView.setIpCount(service.allIPs().size());
            serviceView.setHealthyInstanceCount(service.healthyInstanceCount());
//            serviceView.setTriggerFlag(service.triggerFlag() ? "true" : "false");
            serviceViews.add(serviceView);
        }

        result.replace("serviceList", JacksonUtils.transferToJsonNode(serviceViews));
        result.put("count", total);

        return result;
    }
}
